package cn.wwcyc.controller;

import cn.wwcyc.domain.R;
import cn.wwcyc.domain.Role;
import cn.wwcyc.mapper.RoleMapper;
import cn.wwcyc.service.RoleService;
import cn.wwcyc.service.RolemenuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    RoleMapper rm;

    @Autowired
    RoleService rs;

    @Autowired
    RolemenuService rolemenuService;

    @Autowired
    RolemenuService rms;

    @GetMapping("/getlist")
    public List<Role> getList(){
        List<Role> list = rm.selectList(null);
        return list;
    }

    @RequestMapping("/getpage")
    public R<IPage<Role>> getPage(
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam(required=false) String roleName

            ){
        LambdaQueryWrapper<Role> qw = new LambdaQueryWrapper();
        if(!StringUtils.isBlank(roleName))
            qw.like(Role::getRoleName, roleName);

        IPage<Role> page = new Page<>(pageNum, pageSize);
        page = rm.selectPage(page, qw);
        return R.success(page);
    }

    @GetMapping("/getpage1")
    public IPage<Role> getPage1(
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam(required=false) String name,
            @RequestParam(required=false) Integer population
    ){
        LambdaQueryWrapper<Role> qw = new LambdaQueryWrapper();
        if(!StringUtils.isBlank(name))
            qw.like(Role::getRoleName, name);

        IPage<Role> page = new Page<>(pageNum, pageSize);
        page = rm.selectPage(page, qw);
        throw new RuntimeException("qwqwqw");

    }

    @PostMapping
    public Integer save(@RequestBody Role role){
        Integer i = rm.insert(role);
        return i;
    }

    @PostMapping("/edit")
    public Integer updateById(@RequestBody Role role){
        Integer i = rm.updateById(role);
        return i;
    }

    @DeleteMapping
    public R<Integer> delete(@RequestParam Long id){
        Integer i = rs.removeRoleById(id);
        return R.success(i);

    }

    @GetMapping("/{roleId}")
    public R<List<Integer>> getRoleMenuList(@PathVariable Integer roleId){
        List<Integer>  menuList = rms.getMenusByRoleId(roleId);
        return R.success(menuList);
    }

    @PostMapping("/setmenu/{roleId}")
    public void setMenu(@PathVariable Integer roleId, @RequestBody List<Integer> menuIds){
        rms.setRoleMenu(roleId, menuIds);
    }
}
